package com.zcsy.manage.web.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestContext;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.common.SelectInfo;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.Role;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IMenuService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;

/**
 * @Title: RoleController.java
 * @Package： com.zcsy.shop.web
 * @Description: 角色控制器
 * @author tanghan barbadosliy@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2015年7月7日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController {
	
	private static final int MENU_NORMAL = 1;	//正常菜单
	
	private static final int DEFAULT_ROLE = -1;	//默认角色类型

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IMenuService menuService;
    
    @Autowired
    private IDictService dictService;

    /**
     * @Description 获取角色列表
     * @param model
     * @param req
     *            用户请求
     * @return 角色集合
     * @author xujl 850789178@qq.com
     * @date 2016年1月12日
     * @see
     */
    @RequestMapping(value = "roleListOld", method = RequestMethod.GET)
    public String getRoleListOld(Model model,String rId, HttpServletRequest req) {
        try {
            List<Role> roles = roleService.getAll();
            model.addAttribute("roles", roles);
            if (rId != null) {
                Role role = roleService.getRole(rId);
                List<Menu> menus = menuService.queryMenuByRoleId(rId);
                model.addAttribute("roleMenu", menus);
                model.addAttribute("role", role);

            } else {
                Role role = roles.get(0);
                List<Menu> menus = menuService.queryMenuByRoleId(role.getId());
                model.addAttribute("roleMenu", menus);
                model.addAttribute("role", role);
            }
            
            List<Dict> roleTypes = dictService.getDictFromCache("roleType");
            model.addAttribute("roleTypes", roleTypes);
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "system/role/roleList";
    }
    
    @RequestMapping(value = "roleList", method = RequestMethod.GET)
    public String getRoleList(Model model, Integer pNo, Integer pSize, Integer type, String name, HttpServletRequest req) {
    	if(pNo == null){
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
    	List<SelectInfo> permissions = Constants.getPermissionByUser(CommonService.getSessionUser());
    	
    	if(type == null){
    		type = permissions.get(0).getId();//默认选中第一个
    	}
	    
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        
        List<Role> infos = roleService.getRoles(type, name);
        PageInfo<Role> info = new PageInfo<Role>(infos);
        
		model.addAttribute("info", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("type", type);
		model.addAttribute("name", name);
		model.addAttribute("permissions", permissions);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "system/role/roleTable";
    }

    /**
     * @Description 新增角色
     * @param rname
     *            角色名称
     * @param descrip
     *            角色描述
     * @param req
     *            用户的请求
     * @return
     * @author xujl 850789178@qq.com
     * @date 2016年1月12日
     * @see
     */
    @RequestMapping(value = "editRole", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveRole(String rid , String rname, String rdesc, Integer roleType, String[] menus , String[] cells, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        Role record = new Role();
        record.setRoleName(rname);
        record.setDescrip(rdesc);
        record.setRoleType(roleType);

        try {
        	//增加/修改角色
            if (!rid.equals("0")) {
            	record.setId(rid);
                roleService.updateByPrimaryKey(record);
                
                List<String> curroles = CommonService.getSessionUser().getRoleList();
                if(curroles != null && curroles.size() > 0){
                	for(String item : curroles){
                		if(item.equals(rid)){
                			//当前用户拥有这个角色，需要重新登陆
                			result.setObj(rid);
                			break;
                		}
                	}
                }
            } else {
            	record.setId(UniqueNumberUtils.get18UniqueNumber());
                roleService.insert(record);
            }
            
            //修改对应的菜单和小区权限
            roleService.updateRoleMenu(record.getId(), menus);
            roleService.updateRoleCell(record.getId(), cells);
            
            result.setSuccess(true);
        } catch (Exception e) {
        	e.printStackTrace();
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        return result;
    }
    
    
    /** 
     * @Title: roleEdit 
     * @Description: 角色编辑
     * @param @param id 角色ID
     * @param @return     
     * @return RequestJson     
     * @throws 
     */
    @RequestMapping(value = "roleEdit", method = RequestMethod.GET)
    public String roleEdit(Model model, String id, @Context HttpServletRequest req) {
        Role record = new Role();

            if (!id.equals("0")) {
            	record = roleService.getRole(id);
            	List<String> list = new ArrayList<String>();
            	list.add(id);
            	record.setCells(roleService.getCellInfosByRoleId(list));
            	record.setMenus(menuService.queryFunctionsByRoleId(id));
            	
            	//取出角色对应的菜单和小区信息
            	if(record.getCells() != null && record.getCells().size() > 0){
            		StringBuffer buffer = new StringBuffer();
            		for(CellInfo item : record.getCells()){
            			buffer.append(item.getId() + ",");
            		}
            		
            		String cells = buffer.substring(0, buffer.length() - 1);
            		model.addAttribute("selcells", cells);
            	}
            	
            	if(record.getMenus() != null && record.getMenus().size() > 0){
            		StringBuffer buffer = new StringBuffer();
            		for(Menu item : record.getMenus()){
            			buffer.append(item.getId() + ",");
            		}
            		
            		String menus = buffer.substring(0, buffer.length() - 1);
            		model.addAttribute("selmenus", menus);
            	}
            }else{
            	record.setRoleType(DEFAULT_ROLE);
            }
            
            List<SelectInfo> permissions = Constants.getPermissionByUser(CommonService.getSessionUser());
            model.addAttribute("permissions", permissions);
            
            model.addAttribute("role", record);

        
        return "system/role/roleEdit";
    }

    /** 
     * @Title: getRole 
     * @Description: 根据角色ID获取角色信息
     * @param @param model 模型
     * @param @param roleId 角色ID
     * @param @param req 请求REQUEST
     * @param @return     
     * @return RequestJson JSON封装对象
     * @throws 
     */
    @RequestMapping(value = "getRole", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getRole(Model model,@QueryParam("roleId") String roleId, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            Role role = roleService.getRole(roleId);
            result.setObj(role);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }
    
    /** 
     * @Title: getRMenu 
     * @Description: 菜单权限编辑页面
     * @param @param model 模型
     * @param @param roleId 角色ID
     * @param @param req 请求REQUEST
     * @param @return     
     * @return String     JSP页面路径
     * @throws 
     */
    @RequestMapping(value = "getRMenu", method = RequestMethod.GET)
    public String getRMenu(Model model,@QueryParam("roleId") String roleId,@QueryParam("selectcells") String selectcells,@QueryParam("type") Integer type,@QueryParam("menus") String menus, @Context HttpServletRequest req) {
        try {
            if(roleId != null && !"0".equals(roleId) ){
            	//取到当前与角色关联的所有菜单
            	Role role = roleService.getRole(roleId);
                model.addAttribute("role", role);
            }
            model.addAttribute("roleType", type);
            model.addAttribute("selectcells", selectcells);
            if(StringUtils.isEmpty(menus)){
            	List<String> list = roleService.getMenuLeafIdList(roleId , Constants.getFunctionFromUserType(type));
            	model.addAttribute("menuList", list);
            }else{
            	model.addAttribute("menuList", "[" + menus + "]");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "system/role/roleMenu";
    }
    
    @RequestMapping(value="treeData" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson treeData(HttpServletRequest req,@QueryParam("roleType") Integer roleType, @QueryParam("cells[]") String []selectcells, HttpServletResponse response){
        RequestJson result = new RequestJson();
        JSONArray jsonArr=new JSONArray();
        try {
        	int system = Constants.getFunctionFromUserType(roleType);
            List<Menu> list = menuService.getAllBySystem(system);
            
            List<Menu> permissionMenus = new ArrayList<Menu>();
            if(system == Constants.SYSTEM_OPERATION_WEB && !roleService.ifCurrAdmin()){
            	if(CommonService.getSessionUser().getUserType() != Constants.ADMIN_TYPE){
            	//取出覆盖所选小区权限的用户角色,然后再取这些角色下的菜单并集
            		List<String> permissionRoles = roleService.getRoleListByPermissioncellId(selectcells, CommonService.getSessionUser().getRoleList());
                
            		if(CollectionUtils.isNotEmpty(permissionRoles))
            			permissionMenus = menuService.getMenusByRoleIds(system, permissionRoles);
            	}else{
            		permissionMenus = menuService.getMenusByRoleIds(system, CommonService.getSessionUser().getRoleList());
            	}
            }
            
            for(Menu item : list){
            	JSONObject json = new JSONObject();
            	json.put("id", item.getId());
            	json.put("pId", item.getParentId());
            	json.put("name", item.getMenuName());
            	json.put("type", item.getType());
            	
				if (system == Constants.SYSTEM_OPERATION_WEB && !roleService.ifCurrAdmin()) {
					json.put("chkDisabled", "true");

					// 当前用户自己有权限的小区才可选中
					for (Menu j : permissionMenus) {
						if (j.getId().equals(item.getId())) {
							json.put("chkDisabled", "false");
							break;
						}
					}
				}
            	
            	jsonArr.add(json);
            }
            
            result.setMsg(jsonArr.toJSONString());
        }catch (Exception e) {
           e.printStackTrace();
           result.setMsg("操作异常");
           result.setSuccess(false);
        }
        return result;
    }

    @RequestMapping(value = "updateRMenu", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson updateRoleMenu(@RequestParam(value="menus[]") String[] menus,String roleId, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            roleService.updateRoleMenu(roleId, menus);
            result.setSuccess(true);
            result.setObj(RequestContext.getSession().getAttribute(RequestConstants.USER_SESSION_ID));
        } catch (Exception e) {
        	e.printStackTrace();
            result.setMsg("操作异常");
        }
        return result;
    }
    
    @RequestMapping(value = "checkIfRolePermission", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson checkIfRolePermission(@QueryParam("roleId")
    final String roleId, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
        	//角色对应的小区和功能是不是这个人都有
        	if(!roleService.ifCurrAdmin() && !roleService.checkIfRolePermission(roleId)){
        		result.setSuccess(false);
                result.setMsg("您无权限操作此角色");
                return result;
        	}
        } catch (Exception e) {
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        
        return result;
    }

    @RequestMapping(value = "deleteRoleMenus", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson deleteRoleMenus(@QueryParam("roleId")
    final String roleId, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
        	//角色对应的小区和功能是不是这个人都有
        	if(!roleService.ifCurrAdmin() && !roleService.checkIfRolePermission(roleId)){
        		result.setSuccess(false);
                result.setMsg("您无权限操作此角色");
                return result;
        	}
        	
            List<User> list = userService.selectByRoleId(roleId);
            if (list.size() != 0) {
                result.setSuccess(false);
                result.setMsg("该角色已存在用户，无法删除");
            } else {
            	roleService.deleteRoleCells(roleId);
                roleService.deleteRoleMenus(roleId);
                roleService.deleteByPrimaryKey(roleId);
                result.setSuccess(true);
            }
        } catch (Exception e) {
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        return result;
    }
}
